package com.cl.blog.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.entity.BType;
import com.cl.blog.exception.WebException;
import com.cl.blog.service.BTypeService;
import com.cl.blog.mapper.BTypeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author object
 * @description 针对表【b_type】的数据库操作Service实现
 * @createDate 2024-03-14 17:13:59
 */
@Service
public class BTypeServiceImpl extends ServiceImpl<BTypeMapper, BType>
		implements BTypeService {

	@Override
	public List<BType> list(Long id) {
		return this.list(new QueryWrapper<BType>().eq(id != null, "id", id));
	}

	@Override
	public boolean updateType(Integer id, String typeName) {

		BType bType = this.getById(id);
		Assert.notNull(bType, "当前分类不存在了，刷新试一下把");

		bType.setName(typeName);

		return this.updateById(bType);

	}


	// 批量修改数据，返回的是失败的数据
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateBatchType(List<Integer> bTypes, List<String> bTypeNames) {
		/**
		 * bTypes 是修改的id，bTypeNames是修改的名称，一一对应
		 */
		List<BType> list = new ArrayList<>();
		System.out.println("获得的数据id-----" + bTypes);
		System.out.println("获得的数据Name-----" + bTypeNames);
		for (int i = 0; i < bTypes.size(); i++) {
			BType bType = new BType();
			bType.setId(bTypes.get(i));
			bType.setName(bTypeNames.get(i));

			bType.setUpdateTime(LocalDateTime.now());
			list.add(bType);
		}


		return this.updateBatchById(list);


	}

	@Override
	public Object saveName(String names) {
		// 数据处理
		String[] split = names.split(",");
		List<String> list = Arrays.asList(split);
		System.out.println("初始字符串-----"+split);
		System.out.println("处理的字符串-----"+list);
		List<String> exist = new ArrayList<>();
		List<BType> bTypes = new ArrayList<>();
		for (String s : list){
			BType bType = this.getOne(new QueryWrapper<BType>().eq("name", s));
			if (bType!=null){
				exist.add(bType.getName());
			}else{
				BType type = new BType();
				type.setName(s);
				type.setCreateTime(LocalDateTime.now());
				bTypes.add(type);
			}
		}
		if(bTypes.size()<=0){
			throw new WebException("抱歉，当前添加数据为空，可能是当前新增分类已存在");
		}
		boolean b = this.saveBatch(bTypes);
		if (!b){
			throw new WebException("新增失败");
		}

		return list;
	}
}




